package org.giovanolli.mumi.service.impl;

import java.util.Date;
import java.util.List;

import org.giovanolli.mumi.dao.AttentionTimeDao;
import org.giovanolli.mumi.dao.Dao;
import org.giovanolli.mumi.entities.AttentionTime;
import org.giovanolli.mumi.entities.AttentionTimeStatus;
import org.giovanolli.mumi.entities.Movement;
import org.giovanolli.mumi.entities.MovementType;
import org.giovanolli.mumi.entities.Patient;
import org.giovanolli.mumi.entities.filter.AttentionTimeFilter;
import org.giovanolli.mumi.service.AttentionTimeService;
import org.giovanolli.mumi.service.MovementService;
import org.giovanolli.mumi.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// TODO: Auto-generated Javadoc
/**
 * The Class AttentionTimeServiceImpl.
 */
@Service("attentionTimeService")
public class AttentionTimeServiceImpl extends AbstractService<AttentionTime> implements AttentionTimeService {

	/** The attention time dao. */
	@Autowired
	private AttentionTimeDao attentionTimeDao;

	@Autowired
	private PatientService patientService;

	@Autowired
	private MovementService movementService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.service.BaseObjectService#getServiceDao()
	 */
	protected Dao<AttentionTime> getServiceDao() {
		return attentionTimeDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.service.AttentionTimeService#getNonBilledAttentionTimes (org.giovanolli.mumi.entities.Patient)
	 */
	@Override
	public List<AttentionTime> getNonBilledAttentionTimes(Patient patient) {
		AttentionTimeFilter filter = new AttentionTimeFilter();
		filter.setPatient(patient);
		filter.setIsBilled(false);
		List<AttentionTime> list = attentionTimeDao.getList(filter);
		return list;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.service.AttentionTimeService#confirmAttentionTime (org.giovanolli.mumi.entities.AttentionTime)
	 */
	@Override
	public void confirmAttentionTime(AttentionTime attentionTime) throws Exception {
		if (AttentionTimeStatus.CONFIRMED.equals(attentionTime.getAttentionTimeStatus())) {
			throw new Exception("El turno ya habia sido confirmado");
		}
		Patient patient = attentionTime.getPatient();
		Movement movement = new Movement();
		movement.setDate(new Date());
		movement.setFee(attentionTime.getSpecialistFee().getAmount());
		movement.setMovementType(MovementType.NEGATIVE);
		movement.setSpecialistFee(attentionTime.getSpecialistFee());
		patient.getMovements().add(movement);
		patientService.saveEntity(patient);

		attentionTime.setAttentionTimeStatus(AttentionTimeStatus.CONFIRMED);
		attentionTimeDao.save(attentionTime);
	}

	@Override
	public void saveEntity(AttentionTime entity) {
		if (entity.getAttentionTimeStatus() == null) {
			entity.setAttentionTimeStatus(AttentionTimeStatus.NEW);
		}
		super.saveEntity(entity);
	}

}
